package logic

import (
	"context"
	"encoding/json"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentBatchStatisticsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentBatchStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentBatchStatisticsLogic {
	return AgentBatchStatisticsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentBatchStatisticsLogic) AgentBatchStatistics(req *types.AgentBatchStatisticsReq) (resp interface{}, err error) {

	// 获取当前用户ID
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		l.Error("获取用户id失败", err)
		return nil, err
	}
	req.AgentId = uid

	// 请求参数
	reqStr, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}

	// 调用休闲吧接口
	bytes, err := tools.RequestOtherPlatform(
		l.svcCtx.Config.XiuXianApi.AgentBatchStatistics,
		"POST",
		l.svcCtx.Config.Auth.AccessSecret,
		string(reqStr),
		l.svcCtx.Config.Auth.AccessExpire,
		10000, // admin_users表 下楼系统账户的ID
	)

	if err != nil {
		return nil, err
	}

	// 解析返回数据
	var res *types.AgentBatchStatisticsResp
	err = json.Unmarshal(bytes, &res)
	if err != nil {
		return nil, errorx.NewMsgReasonCodeError(errorx.DefaultCode, "分页查询代理卡片批次的数据统计 err：%v", err.Error())
	}

	// 获取用户信息
	userResp, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{
		Id: uid,
	})
	if err != nil {
		return nil, errorx.NewMsgReasonCodeError(errorx.DefaultCode, "获取用户信息 err：%v", err.Error())
	}

	// 查询指定卡已激活绑定用户数
	for i := range res.Data.Data {
		if res.Data.Data[i].ActiveCardIds == "" {
			res.Data.Data[i].ActiveBindCount = 0
		} else {
			countResp, err := l.svcCtx.AgentRpc.FindActiveBindCountByCatdIDs(l.ctx, &agentClient.FindActiveBindCountByCatdIDsReq{
				Ids: res.Data.Data[i].ActiveCardIds,
			})
			if err != nil {
				return nil, err
			}
			res.Data.Data[i].ActiveBindCount = countResp.Count
		}
		res.Data.Data[i].ActiveCardIds = ""
		res.Data.Data[i].RealName = userResp.RealName
	}

	return res.Data, err
}
